import Vue from 'vue'
import { baseUtils } from './base.js';

//分享地址
Vue.prototype.$shareUrl = 'http://share.xiaomajiankao.com/';

//提示信息
Vue.prototype.$sys = ()=>{
	return uni.getSystemInfoSync()
}
//清除本地local所有 不包括
//重新登录需要删除的缓存信息
Vue.prototype.$clearLocal = ()=>{
	let keys = [
		'token','userInfo','card_meth','wxAccount'
	];
	//清除些东西
	for(let i=0;i<keys.length;i++){
		uni.removeStorageSync(keys[i]);
	}
};
//提示信息
Vue.prototype.$showToast = (msg)=>{
	uni.showToast({
		title:msg,
		duration:2000,
		icon:'none'
	})
}
//copy
Vue.prototype.$copy = (data)=>{
	uni.setClipboardData({
		data:data,
		success:function(res){
			uni.showToast({
				title:'复制成功',
				icon:'none',
				duration:2000
			})
		}
	})
}
//拨打电话
/*
* @params phoneNum 电话号码
*/
Vue.prototype.$call = (phoneNum)=>{
	if(phoneNum == '' || phoneNum == null){
		uni.showToast({
			title:'联系方式有误',
			duration:2000,
			icon:'none'
		});
		return false;
	};
	uni.showActionSheet({
		itemList:['立即拨打电话'],
		success() {
			uni.makePhoneCall({
				phoneNumber:phoneNum,
				fail: (e) => {
					uni.showToast({
						title:'拨打失败，请允许app才能使用',
						duration:2000,
						icon:'none'
					})
				}
			})
		}
	})
}

//字典表转化
Vue.prototype.$getDict = (list,key) =>{
    let name = '-';
    list.forEach(item=>{
        if(item.value == key){
            name = item.label;
        }
    })
    return name
}

//检查定位
Vue.prototype.$checkLocation = () =>{
    let system = uni.getSystemInfoSync();// 获取系统信息
	let bol = true;
	if (system.platform === 'android') { // 判断平台
		var context = plus.android.importClass("android.content.Context");
		var locationManager = plus.android.importClass("android.location.LocationManager");
		var main = plus.android.runtimeMainActivity();
		var mainSvr = main.getSystemService(context.LOCATION_SERVICE);
		bol = mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER);
	}
	return bol
}
//打开定位
Vue.prototype.$openLocation = () =>{
	var context = plus.android.importClass("android.content.Context");
	var locationManager = plus.android.importClass("android.location.LocationManager");
	var main = plus.android.runtimeMainActivity();
	var mainSvr = main.getSystemService(context.LOCATION_SERVICE);
	if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
		var Intent = plus.android.importClass('android.content.Intent');
		var Settings = plus.android.importClass('android.provider.Settings');
		var intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
		main.startActivity(intent); // 打开系统设置GPS服务页面
	} else {
		uni.showToast({
			title:'已经打开定位功能,请刷新',
			duration:2000,
			icon:'none'
		})
	}
}
//导航
/*
*	@params longitude 经度
* 	@params latitude 纬度
* 	@params	stationName 目的地名称
*   都是百度坐标
*/
Vue.prototype.$goLocation = (longitude,latitude,stationName) =>{
	let url = '';
	//baidu 坐标转高德坐标
	let gdPoint = baseUtils.bd_decrypt(longitude,latitude);
	//Android
	if(plus.os.name == 'Android'){
		var hasTencentMap = plus.runtime.isApplicationExist({pname:'com.tencent.map',action:'qqmap://'});
		var hasBaiduMap = plus.runtime.isApplicationExist({pname:'com.baidu.BaiduMap',action:'baidumap://'});
		var hasAmap = plus.runtime.isApplicationExist({pname:'com.autonavi.minimap',action:'androidamap://'});
		//苹果地图
		var appleMap = "http://maps.apple.com/?q="+stationName+"&ll="+gdPoint.lat+","+gdPoint.lng+"&spn=0.008766,0.019441";
		//腾讯地图
		var urlTmap = "qqmap://map/marker?marker=coord:"+gdPoint.lat+","+gdPoint.lng+";title:"+stationName+";addr:加油站&referer=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77";
		//百度地图
		var urlBaiduMap = "baidumap://map/marker?location="+latitude+","+longitude+"&title="+stationName+"&src=tyj";
		//高德地图
		var urlAmap = "androidamap://viewMap?sourceApplication=tyj&poiname="+stationName+"&lat="+gdPoint.lat+"&lon="+gdPoint.lng+"&dev=0";


		let arrs = [];
		if(hasBaiduMap && hasAmap && hasTencentMap){
			arrs = [
				{title:"百度地图",url:urlBaiduMap},{title:"高德地图",url:urlAmap},{title:"腾讯地图",url:urlTmap}
			]
		}else if(hasBaiduMap && hasAmap){
			arrs = [
				{title:"百度地图",url:urlBaiduMap},{title:"高德地图",url:urlAmap}
			]
		}else if(hasBaiduMap && hasTencentMap){
			arrs = [
				{title:"百度地图",url:urlBaiduMap},{title:"腾讯地图",url:urlTmap}
			]
		}else if(hasTencentMap && hasAmap){
			arrs = [
				{title:"腾讯地图",url:urlTmap},{title:"高德地图",url:urlAmap}
			]
		}else if(hasBaiduMap){
			arrs = [
				{title:"百度地图",url:urlBaiduMap}
			]
		}else if(hasAmap){
			arrs = [
				{title:"高德地图",url:urlAmap}
			]
		}else if(hasTencentMap){
			arrs = [
				{title:"腾讯地图",url:urlTmap}
			]
		}
		if(arrs.length <= 0){
			//用户自己手动选择地图
			url = "geo:"+latitude+","+longitude+"?q="+stationName;
			plus.runtime.openURL(url);
		}else{
			plus.nativeUI.actionSheet({
				title:"选择地图应用",
				cancel:"取消",
				buttons:arrs,
			}, function(e){
				plus.runtime.openURL(arrs[e.index-1].url);
			});
		}
		return false;
		if(hasBaiduMap && hasAmap && hasTencentMap){
			plus.nativeUI.actionSheet({
				title:"选择地图应用",
				cancel:"取消",
				buttons:[{title:"百度地图"},{title:"高德地图"},{title:"腾讯地图"}],
			}, function(e){
				switch (e.index){
					case 1:
						plus.runtime.openURL(urlBaiduMap);
						break;
					case 2:
						plus.runtime.openURL(urlAmap);
						break;
					case 3:
						plus.runtime.openURL(urlTmap);
						break;
				}
			})
		}else if(hasBaiduMap && hasAmap){
			plus.nativeUI.actionSheet({
				title:"选择地图应用",
				cancel:"取消",
				buttons:[{title:"百度地图"},{title:"高德地图"}],
			}, function(e){
				switch (e.index){
					case 1:
						plus.runtime.openURL(urlBaiduMap);
						break;
					case 2:
						plus.runtime.openURL(urlAmap);
						break;
				}
			})
		}else if(hasBaiduMap){
			plus.nativeUI.actionSheet({
				title:"选择地图应用",
				cancel:"取消",
				buttons:[{title:"百度地图"}],
			}, function(e){
				switch (e.index){
					case 1:
						plus.runtime.openURL(urlBaiduMap);
						break;
				}
			})
		}else if(hasAmap){
			plus.nativeUI.actionSheet({
				title:"选择地图应用",
				cancel:"取消",
				buttons:[{title:"高德地图"}],
			}, function(e){
				switch (e.index){
					case 1:
						plus.runtime.openURL(urlAmap);
						break;
				}
			})
		}else if(hasTencentMap){
			plus.nativeUI.actionSheet({
				title:"选择地图应用",
				cancel:"取消",
				buttons:[{title:"腾讯地图"}],
			}, function(e){
				switch (e.index){
					case 1:
						plus.runtime.openURL(urlTmap);
						break;
				}
			})
		}else{
			//用户自己手动选择地图
			url = "geo:"+latitude+","+longitude+"?q="+stationName;
			plus.runtime.openURL(url);
		}
	}else{
		plus.nativeUI.actionSheet({
			title:"选择地图应用",
			cancel:"取消",
			buttons:[
				{title:"Apple地图"},
				{title:"百度地图"},
				{title:"高德地图"},
				{title:"腾讯地图"}
			]},
			function(e){
				switch (e.index){
					case 1:
						url = "http://maps.apple.com/?q="+stationName+"&ll="+gdPoint.lat+","+gdPoint.lng+"&spn=0.008766,0.019441";
						break;
					case 2:
						url = "baidumap://map/marker?location="+latitude+","+longitude+"&title="+stationName+"&src=tyj&content=加油站";
						break;
					case 3:
						url = "iosamap://viewMap?sourceApplication=tyj&poiname="+stationName+"&lat="+gdPoint.lat+"&lon="+gdPoint.lng+"&dev=0";
						break;
					case 4:
						url = "qqmap://map/marker?marker=coord:"+gdPoint.lat+","+gdPoint.lng+";title:"+stationName+";addr:加油站&referer=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77";
						break;
					default:
						break;
				}
				if (url!="") {
					console.log(111,url)
					url = encodeURI(url);
					plus.runtime.openURL( url, function( e ) {
						plus.nativeUI.alert("本机未安装指定的地图应用!");
					});
				}
			}
		);
	}
}
//路由跳转
Vue.prototype.$navTo = (url)=>{
	uni.navigateTo({
		url:url
	})
}
//路由跳转
Vue.prototype.$navBack = (url)=>{
	uni.navigateBack({})
}
//路由跳转
Vue.prototype.$tabTo = (url)=>{
	uni.switchTab({
		url:url
	})
}
//路由跳转
Vue.prototype.$redTo = (url)=>{
	uni.redirectTo({
		url:url
	})
}
//路由跳转
Vue.prototype.$relTo = (url)=>{
	uni.reLaunch({
		url:url
	})
}
//协议跳转
Vue.prototype.$toXy = (title,code)=>{
	uni.navigateTo({
		url:`../xyBooks/xyBooks?xy=${code}&title=${title}`
	})
}
//空方法
Vue.prototype.$stopEvent = ()=>{}
//查看图片
Vue.prototype.$wathcImg = (list,index)=>{
	const _this =this;
	index = index || 0;
	uni.previewImage({
		current:index,
		urls:list
	});

	// let app = plus.os.name;
	// if(app == 'Android'){
	// 	uni.previewImage({
	// 		current:index,
	// 		urls:list
	// 	})
	// }else{
	// 	let lists = [];
	// 	uni.showLoading({
	// 		title:'请稍后...',
	// 		mask:true,
	// 	})
	// 	for(let i =0;i<list.length;i++){
	// 		uni.downloadFile({
	// 			url:list[i],
	// 			success:(res)=>{
	// 				if (res.statusCode === 200) {
	// 					lists.push(res.tempFilePath);
	// 					if(list.length == lists.length){
	// 						uni.hideLoading();
	// 						uni.previewImage({
	// 							current:index,
	// 							urls:lists
	// 						})
	// 					}
	// 				}else{
	// 					uni.hideLoading();
	// 				}
	// 			},
	// 			fail: () => {
	// 				uni.hideLoading();
	// 			}
	// 		})
	// 	};
	// }
};
//需要登录
Vue.prototype.$loginAuth = (url)=>{
	return uni.showModal({
		title:'登录',
		content:'您还没有登录，去登录？',
		confirmText:'去登录',
		confirmColor:'#0984FF',
		success:function(res){
			if(res.confirm){
				uni.showTabBar({});
				uni.navigateTo({
					url:'/pages/login/login'
				})
			}
		}
	});
};
//支付支付
Vue.prototype.$alipay = (datas)=>{
	return new Promise((resolve, reject)=>{
		//支付宝APP支付
		// uni.requestPayment({
		// 	provider: 'alipay',
		// 	orderInfo: datas,
		// 	success: (res) => {
		// 		uni.showToast({
		// 			title:'支付成功',
		// 			icon:'none',
		// 			duration:2000
		// 		})
		// 		resolve();
		// 	},
		// 	fail:err=>{
		// 		uni.showToast({
		// 			title:'支付失败',
		// 			icon:'none',
		// 			duration:3000
		// 		});
		// 		reject(err);
		// 	}
		// });
		//支付包沙箱支付
		const jyAliPay = uni.requireNativePlugin('JY-ALIPAY')
		jyAliPay.show({ // 发起支付
			if_sanbox:true,
			auto_create_order_info:false,
			appid:'',
			rsa2_private:"",
			order_info:datas,
		}, function (result) { // 支付完成回调
			if(result.resultStatus == '9000'){
				uni.showToast({
					title:'支付成功',
					icon:'none',
					duration:2000
				});
				resolve();
			}else{
				uni.showToast({
					title:result.memo,
					icon:'none',
					duration:2000
				});
				reject();
			}
		});
	})
}

//截图 返回文件地址
Vue.prototype.$screenshot=()=>{
	return new Promise((resolve,reject)=>{
		//全屏展示
		plus.navigator.setFullscreen(true);
		let pages = getCurrentPages();
		let page = pages[pages.length - 1];
		let ws = page.$getAppWebview();
		let bitmap = new plus.nativeObj.Bitmap('drawScreen');
		// 将webview内容绘制到Bitmap对象中
		ws.draw(bitmap, () => {
		  // 保存图片到本地
		  bitmap.save("_doc/drawScreen.jpg", {
		    overwrite: true
		  }, res => {
				bitmap.clear(); // 清除Bitmap对象
				plus.navigator.setFullscreen(false);
				resolve(res.target);
		  }, error => {
				plus.navigator.setFullscreen(false);
				bitmap.clear(); // 清除Bitmap对象
				reject(JSON.stringify(error));
		  });
		}, error => {
			plus.navigator.setFullscreen(false);
			reject(JSON.stringify(error));
		}, {
		  check: true, // 设置为检测白屏
		});
	})
}
